package com.atguigu.gulimall.member.service.impl;

import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneException;
import com.atguigu.gulimall.member.exception.UserNameException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {

        MemberEntity entity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity =  memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        //检查用户名和手机号是否唯一 为了让Controller感知异常
        checkphoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        //其他的默认设置
        entity.setNickname(vo.getUserName());

        baseMapper.insert(entity);
    }

    @Override
    public void checkphoneUnique(String phone) throws PhoneException{
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile>0){
            throw new PhoneException();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameException{
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (mobile>0){
            throw new UserNameException();
        }

    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //1、去数据库查询
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct)
                .or()
                .eq("mobile", loginacct));
        if (memberEntity==null){
            //数据库中没有这个人
            return null;
        }else {
            String passwordDB = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDB);
            if (matches){
                //登录成功
                return memberEntity;
            }else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        //登录和注册合并逻辑
        String uid = socialUser.getId();
        //判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity!=null){
            //这个用户已经注册了
             MemberEntity update = new MemberEntity();
             update.setId(memberEntity.getId());
             update.setExpiresIn(Long.parseLong(socialUser.getExpires_in()));
             update.setAccessToken(socialUser.getAccess_token());

             baseMapper.updateById(update);
             memberEntity.setExpiresIn(Long.parseLong(socialUser.getExpires_in()));
             memberEntity.setAccessToken(socialUser.getAccess_token());
             return memberEntity;

        }else {
            //没有查询到当前社交用户对应的记录 需要注册
            MemberEntity regist = new MemberEntity();
            regist.setSocialUid(socialUser.getId());
            regist.setExpiresIn(Long.parseLong(socialUser.getExpires_in()));
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setNickname(socialUser.getName());
            baseMapper.insert(regist);
            return regist;
        }
    }

}
